
const conn = require("../../libs/DB/Conn");
const _ = require("underscore");
const {createSql} = require("./dataAnalysisUtil");

module.exports = async function(params){
    let queryYears = [params.queryYear - 1,params.queryYear]
    let timeRange = [{startTime:`${queryYears[0]}-01-01 00:00:00`,endTime:`${queryYears[1]}-12-31 23:59:59`}];
    let sql = createSql(params.type,params.userDomainId,"month",timeRange,{type:"project"},[params.projectId],null)
    let consumptionResult = await conn(sql.sql,sql.queryIds);
    let timeGroup = _.groupBy(consumptionResult,"dataTime");
    let dataList = [];
    let chartObj = {
        month:[],
        data:[{
            name:"同期",
            data:[]
        },{
            name:"本期",
            data:[],
        }],
    };
    for(let month = 1;month <= 12;month++){
        let paddedMonth = month < 10 ? '0' + month : month;
        let previousYearData = timeGroup[`${queryYears[0]}-${paddedMonth}`];
        let currentYearData = timeGroup[`${queryYears[1]}-${paddedMonth}`];
        let hasPreviousYearData = _.isArray(previousYearData);
        let hasCurrentYearData = _.isArray(currentYearData);
        let data = {
            month:`${month}月`,
            previousYearData:hasPreviousYearData ? previousYearData[0].consumption: "--",
            currentYearData:hasCurrentYearData ? currentYearData[0].consumption : "--",
            yoyRate: hasPreviousYearData && hasCurrentYearData && previousYearData[0].consumption !== 0 ? Math.floor((previousYearData[0].consumption - currentYearData[0].consumption) / previousYearData[0].consumption * 100) / 100 : "--"
        }
        chartObj.month.push(`${month}月`);
        chartObj.data[0].data.push(hasPreviousYearData ? previousYearData[0].consumption : 0);
        chartObj.data[1].data.push(hasCurrentYearData ? currentYearData[0].consumption : 0);
        dataList.push(data);
    }

    return {success:true,dataList:dataList,chartObj:chartObj};

}